package r3.rpc.protocol.codec;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import lombok.extern.slf4j.Slf4j;
import r3.rpc.RpcRequest;
import r3.rpc.protocol.serialization.Serialization;

/**
 * RpcEncoder
 *
 * @author zhoufn
 * @create 2017-12-25 11:06
 **/
@Slf4j
public class RpcEncoder extends MessageToByteEncoder {

    private Serialization serialization;

    public RpcEncoder(Serialization serialization){
        this.serialization = serialization;
    }

    /**
     * Encode a message into a {@link ByteBuf}. This method will be called for each written message that can be handled
     * by this encoder.
     *
     * @param ctx the {@link ChannelHandlerContext} which this {@link MessageToByteEncoder} belongs to
     * @param msg the message to encode
     * @param out the {@link ByteBuf} into which the encoded message will be written
     * @throws Exception is thrown if an error accour
     */
    @Override
    protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception {
        byte[] buffer = serialization.serialize(msg);
        out.writeInt(buffer.length);
        out.writeBytes(buffer);
    }
}
